﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ComponentModel;
using Elentok.Common.Async;
using System.Windows.Threading;
using System.Threading;
using Elentok.Common.Wpf.ViewModels.Dialogs;

namespace Elentok.Common.Wpf.Dialogs
{
  /// <summary>
  /// Interaction logic for ProgressDialog.xaml
  /// </summary>
  public partial class ProgressDialog : Window
  {
    #region Fields

    private IAsyncTask task;

    #endregion

    #region Ctor

    /// <summary>
    /// Initializes a new instance of the progress dialog
    /// </summary>
    public ProgressDialog()
    {
      InitializeComponent();
    }

    #endregion

    #region Public Methods

    /// <summary>
    /// Shows the dialog and runs the action,
    /// </summary>
    /// <param name="task">The task.</param>
    /// <param name="showExceptionDialogOnError">if set to <c>true</c> show exception dialog on exception.</param>
    public void Start(IAsyncTask task, bool showExceptionDialogOnError)
    {
      this.task = task;
      this.task.PropertyChanged += Task_PropertyChanged;
      this.DataContext = task;
      
      ShowDialog();

      this.task.PropertyChanged -= Task_PropertyChanged;

      if (task.Exception != null && showExceptionDialogOnError)
      {
        var viewModel = new ExceptionDialogViewModel(task.Exception);
        var dialog = new Dialog(viewModel);
        dialog.Owner = this.Owner;
        dialog.ShowDialog();
      }
    }


    #endregion

    #region Event Handlers

    private void Task_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
      if (e.PropertyName == AsyncTaskProperties.State)
      {
        if (!this.task.IsWorking())
          Close();
      }
    }

    /// <summary>
    /// Raises the <see cref="System.Windows.Window.ContentRendered"/> event
    /// </summary>
    /// <param name="e"></param>
    protected override void OnContentRendered(EventArgs e)
    {
      base.OnContentRendered(e);

      this.task.Start();
    }
  
    private void CancelButton_Click(object sender, RoutedEventArgs e)
    {
      this.task.Cancel();
    }

    /// <summary>
    /// Raises the <see cref="System.Windows.Window.Closing"/> event
    /// </summary>
    /// <param name="e"></param>
    protected override void OnClosing(CancelEventArgs e)
    {
      base.OnClosing(e);

      if (this.task.State == AsyncTaskState.PendingCancellation)
        e.Cancel = true;
    }

    #endregion
  }
}
